/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.marcelo.agro.totales.gui;

import java.awt.BorderLayout;
import java.util.Collection;
import java.util.List;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import org.marcelo.agro.core.DynamicLookup;
import org.marcelo.agro.core.api.ITotales;
import org.marcelo.agro.entidades.Campanas;
import org.marcelo.agro.entidades.Lotes;
import org.marcelo.agro.entidades.LotesPorCampana;
import org.marcelo.agro.entidades.TipoActividad;
import org.marcelo.agro.entidades.eventos.ActividadesEvent;
import org.marcelo.agro.entidades.noadministrados.Estadisticas;
import org.marcelo.agro.totales.util.TotalesUtil;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.marcelo.agro.totales.gui//BarTotales//EN",
autostore = false)
@TopComponent.Description(preferredID = "BarTotalesTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "org.marcelo.agro.totales.gui.BarTotalesTopComponent")
@ActionReference(path = "Menu/Reportes" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_BarTotalesAction",
preferredID = "BarTotalesTopComponent")
@Messages({
    "CTL_BarTotalesAction=BarTotales",
    "CTL_BarTotalesTopComponent=BarTotales Window",
    "HINT_BarTotalesTopComponent=This is a BarTotales window"
})
public final class BarTotalesTopComponent extends TopComponent implements LookupListener{
    
//    Componentes de FX para el grafico
    private BarChart<String, Number> barChar;
//    private Scene scene;
    private Lookup.Result<List<Estadisticas>> resultEstadisticas;
    private int PANEL_WIDTH_INT = 500, PANEL_HEIGHT_INT= 500;
    private JFXPanel jFXPanel;
    private ITotales it = Lookup.getDefault().lookup(ITotales.class);
    
    final static String VENTANA_LOOKUP= "VistaCampanhasTopComponent";
    
    
    private Lookup.Result<Campanas> resultCampanas;
    private Lookup.Result<LotesPorCampana> resultLCP;
    private Lookup.Result<ActividadesEvent> resultEvent;
    
    private CategoryAxis xAxis = new CategoryAxis();
    private NumberAxis yAxis = new NumberAxis();
    private XYChart.Series series1 = new XYChart.Series();
    
    private void initBar(){
        
//        final JPanel jpanel = new JPanel(new BorderLayout());
//        final JFXPanel barFxPanel = new JFXPanel();
        jFXPanel = new JFXPanel();
        
        Platform.setImplicitExit(false);
        Platform.runLater(new Runnable() {

            @Override
            public void run() {
                
                barChar = new BarChart<String, Number>(xAxis, yAxis);
                barChar.setTitle("Inversion");
                xAxis.setLabel("Lotes");       
                yAxis.setLabel("Valor");
                
                series1.setName("Campania");       
                List<Estadisticas<Campanas>> eaList =   it.getTotales();
                for (Estadisticas<Campanas> ec : eaList){
                    series1.getData().add(
                        new XYChart.Data(ec.getCampoAgrupamiento().getNombre(), ec.getSum())
                    );
                }
        
               barChar.getData().add(series1);  
               
//               jPanel.add(barFxPanel,BorderLayout.CENTER);
       
//               add(jpanel,BorderLayout.CENTER);
                
                Scene scene = new Scene(barChar, PANEL_HEIGHT_INT, PANEL_WIDTH_INT);
//                ((Group) scene.getRoot()).getChildren().add(pieChart);
               jFXPanel.setScene(scene);
                
                
            }
        });
    
    }
    
    private void updateBar(final List<Estadisticas<TipoActividad> > el, final List<Estadisticas<Lotes>> ec){
        Platform.runLater(new Runnable() {

            @Override
            public void run() {
                if (el != null ){
                    xAxis.setLabel("Tipo Actividades");       
                    yAxis.setLabel("Costo");
                    series1.setName("Campania");
                    series1.getData().clear();
                    for (Estadisticas<TipoActividad> dato : el){
                        series1.getData().add(
                            new XYChart.Data(dato.getCampoAgrupamiento().getNombre(), dato.getSum())
                        );
                    }
                }
                if (ec != null) {
                    xAxis.setLabel("Lotes");       
                    yAxis.setLabel("Costos");
                    series1.setName("Campania");
                    series1.getData().clear();
                    for (Estadisticas<Lotes> dato : ec){
                        series1.getData().add(
                            new XYChart.Data(dato.getCampoAgrupamiento().getNombre(), dato.getSum())
                        );
                    }
                    
                }
            }
            
        });

    }
    
    private void initJPanel(){
        jPanel1.setLayout(new BorderLayout());
    }

    public BarTotalesTopComponent() {
        initComponents();
        setName(Bundle.CTL_BarTotalesTopComponent());
        setToolTipText(Bundle.HINT_BarTotalesTopComponent());
//        setLayout(new BorderLayout()); 
        initJPanel();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 380, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 278, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        
        initBar();
        jPanel1.add(jFXPanel, BorderLayout.CENTER);
        
        resultCampanas = WindowManager.getDefault()
                .findTopComponent(VENTANA_LOOKUP).getLookup()
                .lookupResult(Campanas.class);
        resultLCP = WindowManager.getDefault()
                .findTopComponent(VENTANA_LOOKUP).getLookup()
                .lookupResult(LotesPorCampana.class);
        resultEvent = DynamicLookup.getDefault().lookupResult(ActividadesEvent.class);
//        resultCampanas = Utilities.actionsGlobalContext()
//                .lookupResult(Campanas.class);
//        resultLCP = Utilities.actionsGlobalContext()
//                .lookupResult(LotesPorCampana.class);
        
        resultCampanas.addLookupListener(this);
        resultLCP.addLookupListener(this);
        resultEvent.addLookupListener(this);
        //Para actualizar la vista de acuerdo al contexto
        resultChanged(new LookupEvent(resultCampanas));
        resultChanged(new LookupEvent(resultLCP));
        resultChanged(new LookupEvent(resultEvent));
        
        
        
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
        resultCampanas.removeLookupListener(this);
        resultLCP.removeLookupListener(this);
        resultEvent.removeLookupListener(this);
        
        jPanel1.remove(jFXPanel);
        jFXPanel = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public void resultChanged(LookupEvent ev) {
        Lookup.Result r= (Lookup.Result) ev.getSource();
        Collection<? extends LotesPorCampana> lotesPorCampanas;
        Collection<? extends Campanas> listCampanias;
        List<Estadisticas<TipoActividad> > estadisticasLote = null;
        List<Estadisticas<Lotes> > estadisticasCampania = null;
        
        if (r.equals(resultCampanas)) {
            listCampanias = r.allInstances();
            estadisticasCampania = TotalesUtil.getEstadisticasCampania(listCampanias);
        }
        
        else if (r.equals(resultLCP)){
            lotesPorCampanas = r.allInstances();
            estadisticasLote =TotalesUtil.getEstadisticasLote(lotesPorCampanas);
        }
        
        else if (r.equals(resultEvent)) {
            Collection<? extends ActividadesEvent> nodeEvents = r.allInstances();
            for (ActividadesEvent ne : nodeEvents) {
                Campanas c = Utilities.actionsGlobalContext().lookup(Campanas.class);
                if (c != null) {
                    estadisticasCampania = it.getTotales(c);
                }
                else {
                    LotesPorCampana lpc = Utilities.actionsGlobalContext().lookup(LotesPorCampana.class);
                    if (lpc != null) {
                        estadisticasLote = it.getTotales(lpc.getCampanas(), lpc.getLotes());
                    }
                                
                }
            }
        
        }
        updateBar(estadisticasLote, estadisticasCampania);
    }
    
    
}
